package com.google.android.translate;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gtalkservice.IChatListener;
import com.google.android.gtalkservice.IChatSession;
import com.google.android.gtalkservice.IGTalkSession;
import com.google.android.gtalkservice.IGTalkService;

public class Transloid extends Activity {
    /** Called when the activity is first created. */

    private static final String LOG_TAG = "Transloid";

    IGTalkSession mXmppSession = null;
    EditText mTextField;
    Button mSendButton;
    Spinner mSpinner;
    String[] bot_names;
    String username;
    Cursor cursor = null;
    
    private static final int TEXT_MSG = 1; 
    
    private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TEXT_MSG:
				logMessage(msg.obj.toString());
				break;
			default: super.handleMessage(msg);
			}
		}
    	
    };
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        this.setTitle(R.string.app_title);
        setContentView(R.layout.main);
        bot_names = getResources().getStringArray(R.array.bot_names);

        mSpinner = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.languages, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        mSpinner.requestFocus();
        username = bot_names[mSpinner.getSelectedItemPosition()]+"@"+getString(R.string.bot_suffix);
//        cursor = managedQuery(Im.Messages.CONTENT_URI, null, null, null, null);
//    	this.getContentResolver().registerContentObserver(Im.Messages.CONTENT_URI, 
//    			false, new ImContentObserver(mHandler));
//        cursor.setNotificationUri(this.getContentResolver(), Im.Messages.CONTENT_URI);

        mTextField = (EditText) findViewById(R.id.message_text);

        mSendButton = (Button) findViewById(R.id.send);
        mSendButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	sendMessage();
            }
        });
        mSendButton.setEnabled(false);

        bindXmppService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }
    
    private void bindXmppService() {
        bindService((new Intent()).setComponent(
                com.google.android.gtalkservice.GTalkServiceConstants.GTALK_SERVICE_COMPONENT),
                mConnection, 0);
    }

    private void logMessage(CharSequence msg) {
        Toast.makeText(Transloid.this, msg,
                Toast.LENGTH_LONG).show();
        
    }
    
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the XmppService has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            IGTalkService xmppService = IGTalkService.Stub.asInterface(service);

            try {
                mXmppSession = xmppService.getDefaultSession();
                if (mXmppSession == null) {
                    // this should not happen.
                    logMessage(getText(R.string.xmpp_session_not_found));
                    return;
                }
            } catch (DeadObjectException ex) {
                Log.e(LOG_TAG, "caught " + ex);
                logMessage(getText(R.string.found_stale_xmpp_service));
            }

            mSendButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mXmppSession = null;
            mSendButton.setEnabled(false);
        }
    };
    

    private void sendMessage() {
        // use XmppService to send data message to someone
    	
        username = bot_names[mSpinner.getSelectedItemPosition()]+"@"+getString(R.string.bot_suffix);
        if (mXmppSession == null) {
            logMessage(getText(R.string.xmpp_service_not_connected));
            return;
        }

        try {
            IChatSession chat = mXmppSession.createChatSession(username);
            chat.addRemoteChatListener(new IChatListener.Stub(){
            	public void newMessageReceived(String from, String body) {
            		mHandler.sendMessage(mHandler.obtainMessage(TEXT_MSG, body));
            	}
            	public void convertedToGroupChat(String oldJid, String groupChatRoom, long groupId){
            		
            	}
            	public void participantJoined(String groupChatRoom, String nickname){
            		
            	}
            	public void participantLeft(String groupChatRoom, String nickname){
            		
            	}
            });
        	chat.sendTextMessage(mTextField.getText().toString());
        } catch (DeadObjectException ex) {
            Log.e(LOG_TAG, "caught " + ex);
            logMessage(getText(R.string.found_stale_xmpp_service));
            mXmppSession = null;
            bindXmppService();
        }
    	
    }

}
